<template>
	<div class="draggable-red-btn" :class="{ hideRight: adsorbSide === 'right', hideLeft: adsorbSide === 'left' }"
		@touchstart="onStart" @touchmove.prevent="onMove" @touchend="onEnd" @click="onClick"
		:style="{top: btnTop, left: btnLeft}">
		运势
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		nextTick,
		getCurrentInstance
	} from 'vue'

	const instance = getCurrentInstance()
	let startX, startY, initLeft, initTop, isDragging = false
	const adsorbSide = ref('') // '' | 'left' | 'right'
	const systemInfo = uni.getSystemInfoSync();
	const btnLeft = ref()
	const btnTop = ref()

	const getRect = () => new Promise(resolve => {
		uni.createSelectorQuery().in(instance).select('.draggable-red-btn')
			.boundingClientRect(resolve).exec()
	})

	/* 初始化位置：右侧居中 */
	onMounted(async () => {
		await nextTick()

		const w = systemInfo.windowWidth;
		const h = systemInfo.windowHeight;

		btnLeft.value = `${w - 90}px`
		btnTop.value = `${h / 2 + 50}px`
	})

	async function onStart(e) {
		isDragging = true
		const touch = e.touches[0]
		startX = touch.clientX
		startY = touch.clientY
		const rect = await getRect()
		initLeft = rect.left
		initTop = rect.top
		adsorbSide.value = '' // 拖动时先取消吸附
	}

	function onMove(e) {
		if (!isDragging) return
		const touch = e.touches[0]
		let newLeft = initLeft + (touch.clientX - startX)
		let newTop = initTop + (touch.clientY - startY)

		/* 边界限制 */
		newLeft = Math.max(0, Math.min(newLeft, systemInfo.windowWidth - 60))
		newTop = Math.max(0, Math.min(newTop, systemInfo.windowHeight - 60))

		btnLeft.value = newLeft + 'px'
		btnTop.value = newTop + 'px'
	}

	async function onEnd() {
		if (!isDragging) return
		isDragging = false

		const rect = await getRect()
		const margin = 30 // 吸附阈值
		if (rect.left < margin) {
			adsorbSide.value = 'left'
		} else if (systemInfo.windowWidth - rect.right < margin) {
			adsorbSide.value = 'right'
		} else {
			adsorbSide.value = ''
		}
	}

	function onClick() {
		if (isDragging) return
		/* 如果处于吸附状态，先弹出；否则跳转 */
		if (adsorbSide.value) {
			adsorbSide.value = ''
		} else {
			uni.navigateTo({
				url: '/src/pages/horoscope/horoscope'
			})
		}
	}
</script>

<style scoped>
	.draggable-red-btn {
		position: fixed;
		z-index: 9999;
		width: 60px;
		height: 60px;
		line-height: 60px;
		text-align: center;
		color: #fff;
		background: #e60012;
		border-radius: 50%;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
		transition: transform 0.3s;
	}

	/* 向右隐藏：只露 28px */
	.hideRight {
		transform: translateX(calc(100% - 28px));
	}

	/* 向左隐藏：只露 28px */
	.hideLeft {
		transform: translateX(-28px);
	}
</style>